/**
 * 全局配置管理
 * 统一管理系统配置和主题设置
 */
class GlobalConfig {
    constructor() {
        this.config = {
            // 系统基础配置
            system_name: '图书馆管理系统',
            library_name: '成都工业学院图书馆',
            system_version: '1.0.0',
            copyright_info: '© 2024 成都工业学院',
            
            // 系统运行参数
            password_min_length: '6',
            password_max_length: '20',
            maintenance_mode: 'false'
        };
        
        this.init();
    }

    async init() {
        await this.loadConfig();
        this.applyTheme();
        this.bindThemeToggle();
    }

    // 加载系统配置
    async loadConfig() {
        try {
            const response = await fetch('/api/system/config/all');
            if (response.ok) {
                const result = await response.json();
                if (result.result === 'SUCCESS' && result.data) {
                    // 将配置数组转换为对象
                    const configObj = {};
                    result.data.forEach(item => {
                        configObj[item.configKey] = item.configValue;
                    });
                    this.config = { ...this.config, ...configObj };
                }
            }
        } catch (error) {
            console.warn('加载系统配置失败，使用默认配置:', error);
        }
    }

    // 应用主题
    applyTheme() {
        const theme = this.config.themeColor || 'light';
        document.documentElement.setAttribute('data-theme', theme);
        
        // 更新主题切换按钮状态
        const themeToggle = document.querySelector('.theme-toggle');
        if (themeToggle) {
            const isDark = theme === 'dark';
            themeToggle.classList.toggle('active', isDark);
            
            const icon = themeToggle.querySelector('i');
            if (icon) {
                icon.className = isDark ? 'fas fa-sun' : 'fas fa-moon';
            }
        }
    }

    // 切换主题
    async toggleTheme() {
        const currentTheme = this.config.themeColor || 'light';
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        
        try {
            const response = await fetch('/api/system/config/set', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    configKey: 'theme_color',
                    configValue: newTheme,
                    description: '主题颜色'
                })
            });

            if (response.ok) {
                const result = await response.json();
                if (result.result === 'SUCCESS') {
                    this.config.themeColor = newTheme;
                    this.applyTheme();
                }
            }
        } catch (error) {
            console.error('切换主题失败:', error);
        }
    }

    // 绑定主题切换事件
    bindThemeToggle() {
        const themeToggle = document.querySelector('.theme-toggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', () => {
                this.toggleTheme();
            });
        }
    }

    // 检查维护模式
    async checkMaintenanceMode() {
        try {
            const response = await fetch('/api/system/config/maintenance/status');
            if (response.ok) {
                const result = await response.json();
                if (result.result === 'SUCCESS' && result.data) {
                    if (result.data.maintenanceMode) {
                        // 如果当前不在维护页面，则跳转
                        if (!window.location.pathname.includes('maintenance.html')) {
                            window.location.href = 'maintenance.html';
                        }
                        return true;
                    }
                }
            }
        } catch (error) {
            console.warn('检查维护模式失败:', error);
        }
        return false;
    }

    // 获取配置值
    getConfig(key) {
        return this.config[key];
    }

    // 设置配置值
    setConfig(key, value) {
        this.config[key] = value;
    }

    // 获取所有配置
    getAllConfig() {
        return { ...this.config };
    }

    // 验证密码长度
    validatePasswordLength(password) {
        const minLength = parseInt(this.config.password_min_length) || 6;
        const maxLength = parseInt(this.config.password_max_length) || 20;
        
        console.log('密码验证:', { minLength, maxLength, passwordLength: password.length });
        
        if (password.length < minLength) {
            return {
                valid: false,
                message: `密码长度不能少于${minLength}位`
            };
        }
        
        if (password.length > maxLength) {
            return {
                valid: false,
                message: `密码长度不能超过${maxLength}位`
            };
        }
        
        return { valid: true };
    }
}

// 创建全局配置实例
window.globalConfig = new GlobalConfig();

// 确保页面加载完成后配置已初始化
document.addEventListener('DOMContentLoaded', function() {
    if (window.globalConfig && typeof window.globalConfig.init === 'function') {
        window.globalConfig.init().catch(error => {
            console.error('全局配置初始化失败:', error);
        });
    }
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    if (window.globalConfig) {
        window.globalConfig.init();
    }
});

// 导出配置类供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = GlobalConfig;
}